package main;

import java.io.IOException;
import java.util.List;

import cn.ideaframe.core.util.DataRow;

import com.itextpdf.text.Document;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.Element;
import com.itextpdf.text.Font;
import com.itextpdf.text.Image;
import com.itextpdf.text.Phrase;
import com.itextpdf.text.pdf.BaseFont;
import com.itextpdf.text.pdf.ColumnText;
import com.itextpdf.text.pdf.PdfContentByte;
import com.itextpdf.text.pdf.PdfPTable;
import com.itextpdf.text.pdf.PdfPageEventHelper;
import com.itextpdf.text.pdf.PdfTemplate;
import com.itextpdf.text.pdf.PdfWriter;

public class ReportHeaderFooter extends PdfPageEventHelper {

	// 模板
	public PdfTemplate total;
	String header;
	public Boolean IsEndPage=false;
	public boolean isPageCon=false;
	
	public DataRow Headers;
	public DataRow Footers;

	DocumentInfo docInfo;
	public PdfPTable t;
	BaseFont bf;
	Font fontDetail;
	public ReportHeaderFooter(DocumentInfo docInfo) {
		this.docInfo=docInfo;
	}


	public void setHeader(String header) {
		this.header = header;
	}


	public void setBf(BaseFont bf) {
		this.bf = bf;
	}

	/**
	 * 
	 * TODO 文档打开时创建模板
	 * 
	 * @see com.itextpdf.text.pdf.PdfPageEventHelper#onOpenDocument(com.itextpdf.text.pdf.PdfWriter,
	 *      com.itextpdf.text.Document)
	 */
	public void onOpenDocument(PdfWriter writer, Document document) {
		total = writer.getDirectContent().createTemplate(50, 50);// 共 页 的矩形的长宽高
	}

	/**
	 * 
	 * TODO 关闭每页的时候，写入页眉，写入'第几页共'这几个字。
	 * 
	 * @see com.itextpdf.text.pdf.PdfPageEventHelper#onEndPage(com.itextpdf.text.pdf.PdfWriter,
	 *      com.itextpdf.text.Document)
	 */
	public void onEndPage(PdfWriter writer, Document document) {
		
		try {
			if (bf == null) {
				bf = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", false);
			}
			if (fontDetail == null) {
				fontDetail = new Font(bf, docInfo.getDefFontSize(), Font.NORMAL);// 数据体字体
			}
		} catch (DocumentException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		
		if(!isPageCon){
			
		}
		
		float len = bf.getWidthPoint(header, docInfo.getTitleSize());
		float topstart = document.top() + document.topMargin()- docInfo.getTitleTop();

		// 1.写入页眉
		ColumnText
				.showTextAligned(
						writer.getDirectContent(),
						Element.ALIGN_CENTER,
						new Phrase(header, fontDetail),
						(document.rightMargin() + document.right()
								+ document.leftMargin() - document.left() - len) / 2.0F + 20F,
						topstart , 0);

		HeaderFooterModel model;
		String nameStr;

		// 文件头部信息

		float tops = topstart-docInfo.getTitleHeight();
		float flen;
		float widths = document.right()-document.rightMargin() -document.leftMargin() - document.left();
		float leftstart=document.leftMargin();
		if (null != docInfo.getHeaderColumns()) {
			int k = 0;
			for (int columns :  docInfo.getHeaderColumns()) {

				
				float width = widths / columns;

				for (int i = 0; i < columns; i++) {
					model =  docInfo.getHeaderModels().get(k);
					nameStr = model.name;
					flen = bf.getWidthPoint(nameStr, docInfo.getDefFontSize()) + 20f;
					if (null != Headers) {

						if (model.simpDataType == SimpDataType.imgType) {
							Image jpeg;
							try {
								jpeg = Image.getInstance(Headers
										.GetColumnStr(model.columnname));
								// jpeg.setAlignment(Image.ALIGN_CENTER);
								float imgwidth=40,imgheight=20;
								if(model.getWidth()>0){
									imgwidth=model.getWidth();
								}
								if(model.getHeight()>0){
									imgheight=model.getHeight();
								}
								jpeg.scaleAbsolute(imgwidth,imgheight);
								jpeg.setAbsolutePosition(width * i + flen + leftstart+model.getOffsetx()-imgwidth/2,
										tops+model.getOffsety()-imgheight/3);
								writer.getDirectContent().addImage(jpeg);
							} catch (Exception e) {
								// TODO Auto-generated catch block
								e.printStackTrace();
							}

						} else {
							nameStr = nameStr
									+ Headers.GetColumnStr(model.columnname);
						}
					}
					ColumnText.showTextAligned(writer.getDirectContent(),
							Element.ALIGN_LEFT,
							new Phrase(nameStr, fontDetail), width * i + leftstart+model.getOffsetx(),
							tops+model.getOffsety(), 0);
					k++;
				}
				tops -= docInfo.gethFHeight();
			}
		}
		// 文件脚部信息

		float bots = document.bottom()-10;
		if (null != docInfo.getFooterColumns()) {
			int k = 0;
			for (int columns : docInfo.getFooterColumns()) {

				
				float width = widths / columns;
				leftstart+=12;
				for (int i = 0; i < columns; i++) {
					model = docInfo.getFooterModels().get(k);
					nameStr = model.name;
					flen = bf.getWidthPoint(nameStr, docInfo.getDefFontSize()) + 20f;
					if (null != Footers) {
						if (model.simpDataType == SimpDataType.imgType) {
							Image jpeg;
							try {
								jpeg = Image.getInstance(Footers
										.GetColumnStr(model.columnname));
								// jpeg.setAlignment(Image.ALIGN_CENTER);
								float imgwidth=40,imgheight=20;
								if(model.getWidth()>0){
									imgwidth=model.getWidth();
								}
								if(model.getHeight()>0){
									imgheight=model.getHeight();
								}
								jpeg.scaleAbsolute(imgwidth,imgheight);
								jpeg.setAbsolutePosition(width * i + flen + leftstart+model.getOffsetx()-imgwidth/2,
										bots+model.getOffsety()-imgheight/3);
								writer.getDirectContent().addImage(jpeg);
							} catch (Exception e) {
								// TODO Auto-generated catch block
								e.printStackTrace();
							}

						} else {
							nameStr = nameStr
									+ Footers.GetColumnStr(model.columnname);
						}
					}
					ColumnText.showTextAligned(writer.getDirectContent(),
							Element.ALIGN_CENTER, new Phrase(nameStr,
									fontDetail), width * i + leftstart+model.getOffsetx(),
							bots+model.getOffsety(), 0);
					k++;
				}
				bots -= docInfo.gethFHeight();
			}
		}
		// 2.写入前半部分的 第 X页/共
		int pageS = writer.getPageNumber();
		String foot1 = "第 " + pageS + " 页 /共";
		Phrase footer = new Phrase(foot1, fontDetail);

		// 3.计算前半部分的foot1的长度，后面好定位最后一部分的'Y页'这俩字的x轴坐标，字体长度也要计算进去 = len
		len = bf.getWidthPoint(foot1, docInfo.getDefFontSize());

		// 4.拿到当前的PdfContentByte
		PdfContentByte cb = writer.getDirectContent();

		// 5.写入页脚1，x轴就是(右margin+左margin + right() -left()- len)/2.0F
		// 再给偏移20F适合人类视觉感受，否则肉眼看上去就太偏左了
		// ,y轴就是底边界-20,否则就贴边重叠到数据体里了就不是页脚了；注意Y轴是从下往上累加的，最上方的Top值是大于Bottom好几百开外的。
		ColumnText
				.showTextAligned(
						cb,
						Element.ALIGN_CENTER,
						footer,
						(document.rightMargin() + document.right()
								+ document.leftMargin() - document.left() - len) / 2.0F + 20F,
								bots, 0);

		// 6.写入页脚2的模板（就是页脚的Y页这俩字）添加到文档中，计算模板的和Y轴,X=(右边界-左边界 - 前半部分的len值)/2.0F +
		// len ， y 轴和之前的保持一致，底边界-20
		cb.addTemplate(total, (document.rightMargin() + document.right()
				+ document.leftMargin() - document.left()) / 2.0F + 20F,
				bots); // 调节模版显示的位置

	}

	/**
	 * 
	 * TODO 关闭文档时，替换模板，完成整个页眉页脚组件
	 * 
	 * @see com.itextpdf.text.pdf.PdfPageEventHelper#onCloseDocument(com.itextpdf.text.pdf.PdfWriter,
	 *      com.itextpdf.text.Document)
	 */
	public void onCloseDocument(PdfWriter writer, Document document) {
		// 7.最后一步了，就是关闭文档的时候，将模板替换成实际的 Y 值,至此，page x of y 制作完毕，完美兼容各种文档size。
		total.beginText();
		total.setFontAndSize(bf, docInfo.getDefFontSize());// 生成的模版的字体、颜色
		String foot2 = " " + (writer.getPageNumber()) + " 页";
		total.showText(foot2);// 模版显示的内容
		total.endText();
		total.closePath();

	}
	public void addBlankRow(){
		
		for(int j=0;j<docInfo.getColumnlst().size();j++){			
			t.addCell("");			
		}
	}
}
